#include "udpServer.hpp"
#include <memory>
#include <cstdio>
#include <pthread.h>
#include "onlineUser.h"
using namespace Server;
using namespace std;

// void hand(int _sockfd,string clientip,uint16_t clientport,string message)
// {
//     //通信业务和任务处理业务 充分的解耦
//     FILE* fp = popen(message.c_str(),"r");
//     if(fp == nullptr)
//     {
//         cout<<"popen fail!"<<endl;
//         exit(FILE_ERR);
//     }
//     char buffer[1024];
//     string responce;
//     while(fgets(buffer,sizeof(buffer),fp) != 0)
//     {
//       responce += buffer;
//     }

//     struct sockaddr_in client;
//     bzero(&client,sizeof(client));
//     client.sin_family = AF_INET;
//     client.sin_addr.s_addr = inet_addr(clientip.c_str());
//     client.sin_port = htons(clientport);

//     sendto(_sockfd,responce.c_str(),responce.size(),0,(struct sockaddr*)&client,sizeof(client));

//     pclose(fp);
// }
USER::OnlineUser onlineuser;

void onlineuserhandler(int _sockfd, string clientip, uint16_t clientport, string message)
{
    if (message == "online")
    {
        onlineuser.addUser(clientip, clientport);
    }

    if (message == "offline")
    {
        onlineuser.delUser(clientip, clientport);
    }

    if (onlineuser.IsOnline(clientip, clientport))
    {
        // 已经在线了 可以进行聊天  进行消息的路由
        if(message != "online") 
        onlineuser.boardcastmessage(_sockfd, clientip, clientport, message);
    }
    else
    {
        struct sockaddr_in client;
        bzero(&client, sizeof(client));
        client.sin_family = AF_INET;
        client.sin_addr.s_addr = inet_addr(clientip.c_str());
        client.sin_port = htons(clientport);

        string retmessage = "您当前为离线状态！ 想要与朋友聊天请上线# online";

        sendto(_sockfd, retmessage.c_str(), retmessage.size(), 0, (struct sockaddr *)&client, sizeof(client));
    }
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cerr << "./udpServer  local_port" << endl;
        exit(ARGC_ERR);
    }
    // ./udpServer  port
    uint16_t port = atoi(argv[1]);

    std::unique_ptr<Server::udpServer> user(new udpServer(onlineuserhandler, port));
    user->initServer();
    user->start();

    return 0;
}
